/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package com.dhpollack.rotogss.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dhpollack.rotogss.data.RotoGSSTeams;
import com.dhpollack.rotogss.data.RotoGSSUsers;
import com.dhpollack.rotogss.data.YahooGames;
import com.dhpollack.rotogss.data.YahooGamesStats;
import com.dhpollack.rotogss.data.YahooLeagueTeamStandings;
import com.dhpollack.rotogss.helper.PMF;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * @author davidpl
 *
 */
public class AllStandingsServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6559615719876216215L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        
        if (user != null) {
        	
        	
        	PersistenceManager pm = PMF.get().getPersistenceManager();
        	
        	Key rg_key = new KeyFactory.Builder(RotoGSSUsers.class.getSimpleName(), user.getNickname()).getKey();
        	try {
        		RotoGSSUsers rg_user = pm.getObjectById(RotoGSSUsers.class, rg_key);
        		Set<RotoGSSTeams> rg_teams = rg_user.getYahooTeamsTracked();
        		List<Key> game_keys = new ArrayList<Key>();
        		Map<Key, String> stat_map = new HashMap<Key, String>();
        		for(RotoGSSTeams rg_team : rg_teams) {
                	StringBuilder s = new StringBuilder();
            		s.append(user.getNickname());
            		s.append("\n");
        			log("Key: " + rg_team.getTeamKey());
        			Key league_key = rg_team.getTeamKey().getParent();
        			log("League Key: " + league_key);
        			Key game_key = league_key.getParent();
        			if(!game_keys.contains(game_key)) {
            			try {
                			YahooGames game = pm.getObjectById(YahooGames.class, game_key);
                			Set<YahooGamesStats> game_stats = game.getYahooGamesStats();
                			if(game_stats.iterator().hasNext()) {
                				for(YahooGamesStats game_stat : game_stats) {
                					stat_map.put(game_stat.getStatsKey(), game_stat.getStatDisplayName());
                				}
                			}
            			} catch(Exception e) {
            				log("Something went wrong getting the stats");
            			}
            			game_keys.add(game_key);
        			}
        			Query query = pm.newQuery(YahooLeagueTeamStandings.class);
        			query.setFilter("leagueKey == leagueKeyParam");
        			query.setOrdering("leagueKey, timestamp");
        			query.declareParameters("com.google.appengine.api.datastore.Key leagueKeyParam");
        			try {
            			List<YahooLeagueTeamStandings> results = (List<YahooLeagueTeamStandings>) query.execute(league_key);
            			if(results.iterator().hasNext()) {
                			for(YahooLeagueTeamStandings standing : results) {
                				s.append("\t\t ");
                				s.append(standing.getTimestamp());
                				s.append(" |");
                				s.append(standing.getTeamRank());
                				s.append("|");
                				s.append(standing.getTeamPoints());
            					//stat_map.get(stat.getStatkey());
            					List<Key> stat_keys = standing.getStatKeys();
            					List<Double> stat_values = standing.getStatValues();
            					
            					int stat_num = stat_keys.size();
                				for(int i=0;i<stat_num;i++) {
                    				s.append("|");
                    				s.append(stat_map.get(stat_keys.get(i)));
                    				s.append(": ");
                    				s.append(stat_values.get(i));
                				}
                				s.append("\n");
                			}
            			}
            			resp.getWriter().println(s.toString());
        			} finally {
        				query.closeAll();
        			}
        		}
            	//log(s.toString());
        	} catch(JDOObjectNotFoundException e) {
        		resp.sendRedirect("/start.jsp");
        	}
        } else {
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        }

	}

}
